//调用本地接口
new Vue({
    el: '#app',
    data: {
        messages: [],
        newMessage: '',
        username: ''
    },
    computed: {
        reversedMessages() {
            // 倒序排列留言列表
            return this.messages.slice()
            // return this.messages.slice().reverse();
        }
    },
    created() {
        this.getMessages();
    },
    methods: {
        getMessages() {
            axios.get('http://ip地址:5000/messages')
                .then(response => {
                    this.messages = response.data;
                })
                .catch(error => {
                    console.error('Error fetching messages:', error);
                });
        },
        sendMessage() {
            if (this.newMessage) {
                axios.post('http://ip地址:5000/messages', { username: this.username, message: this.newMessage })
                    .then(response => {
                        this.newMessage = '';
                        
                        this.username = '';
                        this.getMessages(); // 更新留言列表
                    })
                    .catch(error => {
                        alert("发布失败，请联系管理员")
                        console.error('Error posting message:', error);
                    });
            }
        },
        formatDate(timestamp) {
            const date = new Date(timestamp * 1000);
            return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
        },
        formatMessage(message) {
            return message.replace(/\n/g, '<br>');
        }
    }
});